import ky, {Options} from 'ky';
import {ResponseData} from "@/types/utils";
import {showToast} from "@/utils/modules/devices";
import config from "@/config";
import {navigate} from "@/navigators/RootNavigation";
import {useStore} from "@/store";
import {QueryClient} from "@tanstack/react-query";

const prefixUrl = `${config.baseUrl ? config.baseUrl : ''}/`;

export const instance = ky.extend({
    prefixUrl,
    timeout: 5000,
    headers: {
        Accept: 'application/json',
    },
    hooks: {
        beforeRequest: [
            (request, options) => {
                const token = useStore.getState().token;
                if (token) request.headers.set('session', token);
            }
        ],
        beforeError: [
            error => {
                const {response} = error;
                console.log("请求出错了", error)
                return error;
            }
        ],
        afterResponse: [
            async (_request, _options, response) => {
                // You could do something with the response, for example, logging.
                // Or return a `Response` instance to overwrite the response.
                // return new Response('A different response', {status: 200});
                let res = await response.json();
                console.log("响应", _request.url)
                // console.log("响应", _request)
                if (res.code !== 200) {
                    return handleError(res);
                }
                return res;
            },
        ]
    }
});

function handleError(error: ResponseData<any>) {
    let {code, message} = error;
    console.log("报错了", error);
    switch (code) {
        case 0:
        case 500:
            showToast(message, "error");
            break;
        case 10501:
            showToast("系统正在更新,请稍后再试", "error");
            break;
        case 501:
            // 未登录
            showToast(message, "error", {
                callBack: () => {
                    navigate("Login");
                    useStore.getState().reset();
                }
            });
            break;
    }

    return Promise.reject(error);
}


export const addChannelParams = <D>(data?: D) => {
    return {
        channel: useStore.getState().channel,
        ...data,
    }
}
export const addChannelSearchParams = (link: string) => {
    let url = new URL(link);
    url.searchParams.append('channel', String(useStore.getState().channel));
    return url.toString();
}

// 创建 QueryClient 实例
export const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            queryFn: async ({queryKey}) => {
                const [endpoint] = queryKey;
                return instance.get(endpoint as string).json();
            },
        },
    },
})